﻿using System.Threading.Tasks;
using AutoMapper;
using MicroApplication.Common.Auth;
using MicroApplication.Common.Input;
using MicroApplication.Common.Output;
using MicroApplication.Model.Business;
using MicroApplication.Repository.Business;
using MicroApplication.Service.Business.Driver.Input;
using MicroApplication.Service.Business.Driver.Output;

namespace MicroApplication.Service.Business.Driver
{	
    /// <summary>
    /// {{EntityDesc}}业务接口
    /// </summary>
	public class DriverService : IDriverService
    {
        private readonly IUser _user;
        private readonly IMapper _mapper;
        private readonly IDriverRepository _driverRepository;
        public DriverService(
            IUser user,
            IMapper mapper,
            IDriverRepository driverRepository
        )
        {
            _user = user;
            _mapper = mapper;
            _driverRepository = driverRepository;
        }

        public async Task<IResponseOutput> GetAsync(long id)
        {
            var result = await _driverRepository.GetAsync(id);
            return ResponseOutput.Ok(result);
        }

        public async Task<IResponseOutput> PageAsync(PageInput<DriverEntity> input)
        {
            var list = await _driverRepository.Select
            .Count(out var total)
            .OrderByDescending(true, c => c.Id)
            .Page(input.CurrentPage, input.PageSize)
            .ToListAsync<DriverListOutput>();

            var data = new PageOutput<DriverListOutput>()
            {
                List = list,
                Total = total
            };
            
            return ResponseOutput.Ok(data);
        }

        public async Task<IResponseOutput> AddAsync(DriverAddInput input)
        {
            var entity = _mapper.Map<DriverEntity>(input);
            var id = (await _driverRepository.InsertAsync(entity)).Id;

            return ResponseOutput.Result(id > 0);
        }

        public async Task<IResponseOutput> UpdateAsync(DriverUpdateInput input)
        {
            if (!(input?.Id > 0))
            {
                return ResponseOutput.NotOk();
            }

            var entity = await _driverRepository.GetAsync(input.Id);
            if (!(entity?.Id > 0))
            {
                return ResponseOutput.NotOk("数据不存在！");
            }

            _mapper.Map(input, entity);
            await _driverRepository.UpdateAsync(entity);
            return ResponseOutput.Ok();
        }

        public async Task<IResponseOutput> DeleteAsync(long id)
        {
            var result = await _driverRepository.DeleteAsync(id);

            return ResponseOutput.Result(result > 0);
        }
    }
}
